<?php

namespace service;

use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Payment;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Exception;
use repository\PaymentRepositories\PaymentRepositories;
use util\Hook\Hook;

/**
 * 支付宝 Service
 */
class AliPayService
{
    /**
     * 支付宝配置参数设置
     * Author: Albert3306
     * Date: 2020/12/22
     * @return Config
     */
    public static function options()
    {
        $options = new Config();
        $options->protocol          = 'https';
        $options->gatewayHost       = 'openapi.alipay.com/gateway.do';
        $options->signType          = 'RSA2';
        $options->appId             = '';
        $options->notifyUrl         = '';
        $options->merchantPrivateKey= '';
        $options->alipayPublicKey   = '';
        return $options;
    }

    /**
     * 支付
     * Author: Albert3306
     * Date: 2020/12/24
     * @return Payment
     */
    public static function paymentService()
    {
        // 配置参数设置
        Factory::setOptions(self::options());
        return Factory::payment();
    }

    /**
     * APP支付准备
     * Author: Albert3306
     * Date: 2020/12/22
     * @param $outTradeNo
     * @param $totalAmount
     * @param string $subject
     * @return string
     * @throws Exception
     */
    public static function appPaymentPrepare($outTradeNo, $totalAmount, $subject = '')
    {
        try {
            $res = self::paymentService()->app()->pay($subject, $outTradeNo, $totalAmount);
            $responseChecker = new ResponseChecker();
            if ($responseChecker->success($res)) {
                return $res->body;
            } else {
                // 抛出异常 ($res->msg . "，" . $res->subMsg . PHP_EOL);
            }
        } catch (Exception $e) {
            // 抛出异常 ($e->getMessage());
        }
    }

    /**
     * 支付成功回调
     * Author: Albert3306
     * Date: 2020/12/23
     * @param $parameters
     * @return bool
     */
    public static function handleNotify($parameters)
    {
        $res = self::paymentService()->common()->verifyNotify($parameters);
        if ($res && $parameters['trade_status'] == 'TRADE_SUCCESS') {
            if (isset($parameters['subject']) && $parameters['subject']) {
                if (isset($parameters['subject']) && $parameters['subject']) {
                    return (new Hook(PaymentRepositories::class, 'alipay'))->listen($parameters['subject'], $parameters['out_trade_no']);
                }
            }
        }
    }
}